/*
 @Name: layer插件
 @Author: ray
 @License: MIT
 */

; (function (window, $, undef) {
    "use strict";

    var plugName = "layer",
        $win = $(window),
        $doc = $(document),
        globalIndex = 1000,
        dataCache = {},
        isRayui = window.rayui && rayui.define,
        dict = {},
        layer = {
            btns: {
                ok: "确定",
                cancel: "取消"
            },
            globalOptions: {
                anim: 0,
                autoResize: true, //自适应屏幕
                allowMove: true,//是否允许拖拽
                type: 0, //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: "提示",
                timeout: 0,
                shade: true, //遮罩
                shadeClose: false, //遮罩关闭
                shadow: true, //阴影
                btnAlign: "right",
                btnNoColor: 1,
                content: "",
                offset: 5,
                iconAlign: 'left',
                closeBtn: true,
                zIndex: 10000,
                maxWidth: 400,
                maxHeight: 300,
                full: false, //自动全屏
                resize: false, //是否允许改变大小
                scrollbar: true, //是否允许浏览器滚动条
            },
            loadOpt0: {
                rotate: 3, //距离圆点位置
                lines: 12, //线条数量
                length: 8, //线条长度
                lheight: 2, //线条宽度
                radius: 10, //线条圆角
                color: '#000', //线条颜色
                direction: 1, //旋转方向，1顺时针，其他逆时针
                speed: 1 //旋转速度
            }
        },
        LayerClass = function (options) {
            var that = this;
            that.index = globalIndex++;
            options = that.options = $.extend(true, {}, layer.globalOptions, options);

            options.width && options.width > options.maxWidth && (options.maxWidth = options.width);
            options.height && options.height > options.maxHeight && (options.maxHeight = options.height);
            var btnType = typeof options.btns;
            if (btnType === "string") {
                options.btns = [options.btns];
            } else if (btnType === "number") {
                options.btns === 1 && (options.btns = [layer.btns.ok]);
                options.btns === 2 && (options.btns = [layer.btns.ok, layer.btns.cancel]);
            }

            //容器
            var $container = that.$container = $(options.container || "body"),
                shadeStyle = options.type === 2 ? ' style="background-color:#fff"' : '';

            //遮罩
            options.shade &&
                $container.append('<div id="layer-shade-' +
                    that.index +
                    '" class="layer-shade' +
                    (options.container ? " layer-shade-con" : "") +
                    '"' +
                    shadeStyle +
                    '></div>');

            //主体
            var mainHtml = [];
            mainHtml.push('<div id="layer-mainbox-' + that.index);
            mainHtml.push('" class="layer-mainbox');
            mainHtml.push(!options.shadow ? " layer-noshadow" : "");
            mainHtml.push(options.container ? " layer-mainbox-con" : "");
            mainHtml.push('"'); //end class
            mainHtml.push('></div>');
            $container.append(mainHtml.join(''));

            options.$main = $container.find("#layer-mainbox-" + that.index);

            that.init();
            that.addEvents();

            //全屏
            if (options.full) {
                options.$main.find('.layer-toolbox .layer-btn-maximize').click();
            }

            dataCache[that.index] = that;
            typeof options.onShow === "function" && options.onShow.call(options.$main, that);
        };

    LayerClass.prototype.init = function () {
        var that = this,
            index = that.index,
            options = that.options,
            $container = that.$container,
            $shade = $container.find("#layer-shade-" + index),
            $main = options.$main,
            $title,
            $btnbox;

        //浏览器滚动条
        !options.scrollbar && $("html").addClass("overflow-hidden");

        //遮罩样式
        var shadeOpt = {
            "z-index": options.zIndex
        };
        if (options.container) {
            $(options.container).css("position", "relative");
            shadeOpt.top = 0;
            shadeOpt.left = 0;
        }
        if (options.shade && options.shadeOpacity) {
            shadeOpt.opacity = options.shadeOpacity;
            shadeOpt.filter = 'alpha(opacity=' + (options.shadeOpacity * 100) + ');';
        }
        $shade.css(shadeOpt);

        //主体样式
        $main.css({
            "max-width": options.maxWidth + "px",
            "max-height": options.maxHeight + "px",
            "z-index": options.zIndex
        });

        if (options.type === 3) {
            $main.css("min-width", "10px");
        }

        //标题：false|""
        if (options.title) {
            var $tools = $('<div class="layer-toolbox"></div>'),
                hasTools = false;

            $title = $('<div class="layer-titlebox"></div>');
            $title.append('<span class="layer-title">' + options.title + '</span>');

            if (options.minBtn) {
                $tools.append('<a class="rayui-btn btn-text layer-btn-minimize"><i class="ra ra-minimize"></i></a>');
                hasTools = true;
            }
            if (options.maxBtn) {
                $tools.append('<a class="rayui-btn btn-text layer-btn-maximize"><i class="ra ra-maximize"></i></a>');
                hasTools = true;
            }
            hasTools &&
                $tools.append('<a class="rayui-btn btn-text layer-btn-restore hidden"><i class="ra ra-restore"></i></a>');
            if (options.closeBtn) {
                $tools.append('<a class="rayui-btn btn-text layer-btn-close"><i class="ra ra-wrong"></i></a>');
                hasTools = true;
            }
            $main.append($title);
            hasTools && $title.append($tools);
        }

        //内容主体
        var $content = $('<div class="layer-contentbox"></div>');
        $main.append($content);
        that.initContent($content);

        //按钮组
        if (options.btns) {
            var i,
                count = options.btns.length,
                colorsCount = 9,
                isOnAddedBtn = typeof options.onAddedBtn === "function";

            $btnbox = $('<div class="layer-btnbox "></div>');
            if (options.btnAlign !== "right")
                $btnbox.css("text-align", options.btnAlign);

            $main.append($btnbox);
            for (i = 0; i < count; i++) {
                var $btn = $('<a class="rayui-btn" data-index=' + i + '>' + options.btns[i] + '</a>');
                i < options.btnNoColor && $btn.addClass("layer-btn-" + [i < colorsCount ? i : i % colorsCount]);
                $btnbox.append($btn);
                isOnAddedBtn && (options.onAddedBtn.call($btn, i, $btnbox));
            }
        }

        //拉伸大小
        options.resize && $main.append('<span class="layer-resize"></span>');

        //内容主体高度
        if (options.type !== 3) {
            var height = options.height || $main.height();
            //为0时，可能是元素被隐藏导致的，这个时候不再管宽高
            if (height !== 0) {
                options.title && (height -= $title.outerHeight());
                options.btns && (height -= $btnbox.outerHeight());
                $content.outerHeight(height);
            }
        }

        //设置高宽
        var opt = { animation: "layer-anim" + options.anim + " 0.2s" };
        options.width && (opt.width = options.width + "px");
        options.height && (opt.height = options.height + "px");
        $main.css(opt);
        that.setPosition();

        //iframe加载等待
        if (options.icon > 0 && options.type === 1) {
            var iframeIndex = layer.loading({ container: $content });
            $("#layer-iframe-" + index, $content).load(function () {
                layer.close(iframeIndex);
            });
        }
    }

    LayerClass.prototype.initContent = function ($contentBox) {
        var that = this,
            index = that.index,
            options = that.options,
            content = options.content;

        switch (options.type) {
            case 0: //0（信息框，默认）
                if (/^(#|\.)\w+/.test(content) || content instanceof jQuery) {
                    options.contentParent = $(content).parent();
                    $contentBox.append($(content).show());
                } else {
                    $contentBox.append('<div class="layer-content"><span>' + content + "</span></div>");
                }
                //添加图标
                if (options.icon >= 0) {
                    var $cc = $contentBox.find(".layer-content"),
                        $iconBox = $('<div class="layer-iconbox"><i class="ra layer-icon layer-' +
                            (options.type === 2 ? "loading-" : "icon-") +
                            options.icon +
                            '"></i></div>');
                    switch (options.iconAlign) {
                        case 'left':
                            $cc.append($iconBox).addClass("layer-iconbox-left");
                            break;
                        case 'top':
                            $cc.prepend($iconBox).addClass("layer-iconbox-top");
                            break;
                    }
                }
                break;
            case 1: //1（iframe层）
                var id = "layer-iframe-" + index,
                    iframe = [
                        '<iframe ',
                        ' id="' + id + '"',
                        ' name="' + id + '"',
                        ' class="layer-iframe"',
                        ' src="' + content + '"',
                        //' allowTransparency="true"',
                        '></iframe>'
                    ].join('');
                $contentBox.append(iframe).css({
                    padding: "0",
                    overflow: "hidden"
                });
                break;
            case 2: //2（加载层）
                options.$main.addClass("layer-loading-main");
                var $content = $('<div class="layer-content"></div>').appendTo($contentBox);
                switch (content && options.iconAlign) {
                    case 'left':
                        $content.addClass("layer-iconbox-left");
                        break;
                    case 'top':
                        $content.addClass("layer-iconbox-top");
                        break;
                }
                if (options.icon === 0) that.createLoading0($content);
                else if (options.icon > 0) {
                    //gif图片
                    $content.append('<div class="layer-loading' + options.icon + '"></div>');
                    if (content) {
                        //提示内容
                        $('<span>' + content + '</span>').appendTo($content);
                    }
                }
                break;
            case 3: //3（tips层）
                //offset可选2468
                var offset = options.offset,
                    dir = offset === 2 ? 'top' : offset === 4 ? 'left' : offset === 6 ? 'right' : 'bottom';
                $contentBox.append('<div class="layer-content" style="background-color:' +
                    options.bgColor +
                    '"><span>' +
                    content +
                    '</span></div>')
                    .after('<div class="layer-arrow" style="border-' + dir + '-color:' + options.bgColor + '"></div>')
                    .addClass("layer-tips-content")
                    .closest(".layer-mainbox").addClass("layer-tips layer-tips-" + options.offset);
                this.setTipsPosition();
                break;
        }

    }

    LayerClass.prototype.createLoading0 = function ($con) {
        var that = this,
            index = that.index,
            options = that.options,
            content = options.content,
            i = 0,
            $main = $con,
            $lineCon = $('<div class="layer-loading layer-iconbox"/>'),
            $line = $('<div class="layer-loading-line"></div>'),
            loadingOpt = $.extend(true, {}, layer.loadOpt0, options.loadOpt0),
            offsetX = loadingOpt.length + loadingOpt.rotate,
            styles = [
                '#layer-mainbox-' + index + ' .layer-loading-line{',
                'position: absolute',
                ';width:' + loadingOpt.length + "px",
                ';height:' + loadingOpt.lheight + "px",
                ';background-color:' + loadingOpt.color,
                ';border-radius:' + loadingOpt.radius + "px",
                ';left:' + (offsetX) + "px",
                ';top:' + (offsetX + loadingOpt.length / 2 - loadingOpt.lheight / 2) + "px",
                '}'
            ];

        //创建线
        var averAngle = 360 / loadingOpt.lines,
            delayed = loadingOpt.speed / loadingOpt.lines,
            d = (loadingOpt.length / 2 + offsetX) * 2;

        for (; i < loadingOpt.lines; i++) {
            $line.clone().css({
                opacity: '0.2',
                transform: 'rotate(' + (averAngle * i) + 'deg) translate(' + offsetX + 'px' + ', 0)',
                animation: 'layer-loading0 ' +
                    loadingOpt.speed +
                    's  linear ' +
                    ((loadingOpt.direction === 1 ? i : loadingOpt.lines - i) * delayed) +
                    's infinite'
            }).appendTo($lineCon);
        }
        //添加样式、计算高宽
        $lineCon.append("<style>" + styles.join('') + "</style>")
            .css({
                "width": d + "px",
                "height": d + "px"
            })
            .appendTo($main);

        if (content) {
            var $txt = $('<span>' + content + '</span>');
            $txt.appendTo($main);
            //    .css({
            //    "padding-left": d + "px",
            //    "margin-top": $txt.height() / -2 + "px"
            //});
        }
    }

    LayerClass.prototype.addEvents = function () {
        var that = this,
            index = that.index,
            options = that.options,
            $container = that.$container,
            $main = options.$main,$input;

        //自动关闭
        options.timeout > 0 && (options.timerCloseIns = setTimeout(function () { layer.close(index) }, options.timeout));

        //shade关闭
        options.shade &&
            options.shadeClose &&
            $container.find("#layer-shade-" + index).click(function () { layer.close(index) });
        
        //最大化、最小化、关闭
        if (options.title) {
            var $tools = $main.find('.layer-toolbox'), needRestore = false;
            //最小化
            if (options.minBtn) {
                needRestore = true;
                $tools.find('.layer-btn-minimize').click(function () {
                    options.position = $main.position();
                    $main.css({ top: "", left: "" }).addClass("layer-minimize");
                    options.tempContentHeight = $main.find(".layer-contentbox").height();
                });
            }
            //最大化
            if (options.maxBtn) {
                needRestore = true;
                $tools.find('.layer-btn-maximize').click(function () {
                    //不知道为什么使用$main.position()总是有误差
                    options.position = { top: $main.css("top"), left: $main.css("left") };
                    $main.css({ top: "", left: "" }).addClass("layer-maximize");
                    var $conbox = $main.find(".layer-contentbox");
                    options.tempContentHeight = $conbox.height();
                    $conbox.height($win.height() -
                        $main.find(".layer-titlebox").outerHeight() -
                        $main.find(".layer-btnbox").outerHeight());
                });
            }

            //还原
            if (needRestore) {
                $tools.find('.layer-btn-restore').click(function () {
                    $main.css({
                        top: options.position.top,
                        left: options.position.left
                    });
                    $main.removeClass("layer-minimize layer-maximize");
                    $main.find(".layer-contentbox").height(options.tempContentHeight);
                });
            }

            //关闭
            options.closeBtn && $tools.find('.layer-btn-close').click(function () { layer.close(index) });

            //拖动标题
            var $moveDom = $main.find(".layer-titlebox");
            if (options.allowMove) {
                $moveDom.on("mousedown.layer",
                    function (e) {
                        if ($(e.target).closest("div").prop("class").indexOf("layer-toolbox") >= 0) return;
                        //如果最大化则不允许拖动
                        if ($main.prop("class").indexOf("layer-maximize") >= 0) return;
                        dict.type = 0;
                        dict.flag = true;
                        dict.elem = $main;
                        dict.X = e.clientX;
                        dict.Y = e.clientY;
                        var position = $main.position();
                        dict.top = position.top;
                        dict.left = position.left;
                    });
            } else {
                $moveDom.css("cursor", "default");
            }
        }

        //按钮组
        if (options.btns) {
            $main.find(".layer-btnbox").on("click", ".rayui-btn", function (e) {
                var dex = $(this).data("index"), btnfunc = "btn" + dex, func = options[btnfunc];
                typeof func === "function" && func.call(this, index, e);
            });
        }

        //拉伸大小
        $main.find(".layer-resize").on("mousedown." + plugName,
            function (e) {
                e.preventDefault();
                $main.width($main.width());
                $main.css({
                    "max-width": "",
                    "max-height": ""
                });
                var titleHeight = $main.find(".layer-titlebox").outerHeight();
                dict.type = 1;
                dict.elem = $main;
                dict.elemContent = $main.find(".layer-contentbox");
                dict.elemBtnbox = $main.find(".layer-btnbox");
                dict.flag = true;
                dict.width = $main.width();
                dict.height = $main.height() - titleHeight;
                dict.minWidth = parseFloat($main.css("min-width").replace("px", ""));
                dict.minHeight = parseFloat($main.css("min-height").replace("px", "")) - titleHeight;
                dict.X = e.clientX;
                dict.Y = e.clientY;
                dict.shade =
                    $('<div class="full-absolute"/>').appendTo(dict.elemContent); //遮罩，防止移动到iframe不触发mousemove函数
            });

    }

    LayerClass.prototype.setTipsPosition = function () {
        var that = this,
            options = that.options,
            $main = options.$main,
            $arrow = $main.find(".layer-arrow"),
            //offset偏移量格式：123456789,[left, top]
            offset = options.offset,
            cssOpt = {},
            $elem = $(options.elem);

        var tmpOffset = $elem.offset(),
            pleft = tmpOffset.left,
            ptop = tmpOffset.top,
            ewidth = $elem.outerWidth(),
            eheight = $elem.outerHeight(),
            mwidth = $main.outerWidth(),
            mheight = $main.outerHeight(),
            arrowWh = 10;

        switch (offset) {
            //上
            case 2:
                cssOpt.top = ptop - mheight - arrowWh + "px";
                cssOpt.left = pleft + "px";
                $arrow.css("left", (mwidth / 2) + "px");
                break;
            //左
            case 4:
                cssOpt.top = ptop + "px";
                cssOpt.left = pleft - mwidth - arrowWh + "px";
                $arrow.css("top", (eheight / 2) + "px");
                break;
            //右
            case 6:
                cssOpt.top = ptop + "px";
                cssOpt.left = pleft + ewidth + arrowWh + "px";
                $arrow.css("top", (eheight / 2) + "px");
                break;
            //下
            case 8:
                cssOpt.top = ptop + eheight + arrowWh + "px";
                cssOpt.left = pleft + "px";
                $arrow.css("left", (mwidth / 2) + "px");
                break;
        }
        $main.css(cssOpt);
    }

    LayerClass.prototype.setPosition = function () {
        var that = this,
            options = that.options,
            //offset偏移量格式：123456789,[left, top]
            offset = options.offset,
            $parent = $(options.container || $win),
            $main = options.$main,
            cssOpt = {},
            halfLeft = (($parent.width() - $main.outerWidth()) / 2) + "px",
            halfTop = (($parent.height() - $main.outerHeight()) / 2) + "px";

        if (options.type !== 3) {
            switch (offset) {
                case 1:
                    cssOpt.top = 0, cssOpt.left = 0;
                    break;
                case 2:
                    cssOpt.top = 0, cssOpt.left = halfLeft;
                    break;
                case 3:
                    cssOpt.top = 0, cssOpt.right = 0;
                    break;
                case 4:
                    cssOpt.top = halfTop;
                    cssOpt.left = 0;
                    break;
                case 5:
                    cssOpt.top = halfTop;
                    cssOpt.left = halfLeft;
                    break;
                case 6:
                    cssOpt.top = halfTop;
                    cssOpt.right = 0;
                    break;
                case 7:
                    cssOpt.bottom = 0;
                    cssOpt.left = 0;
                    break;
                case 8:
                    cssOpt.bottom = 0;
                    cssOpt.left = halfLeft;
                    break;
                case 9:
                    cssOpt.bottom = 0;
                    cssOpt.right = 0;
                    break;
                default:
                    if (offset instanceof Array) {
                        cssOpt.top = offset[0];
                        cssOpt.left = offset[1];
                    }
                    break;
            }
        }

        $main.css(cssOpt);
    }

    //改变窗体大小
    $win.resize(function () {
        var needReset = [2, 4, 5, 6, 8], diaClass, offset, isArray, isInNeed;
        for (var one in dataCache) {
            diaClass = dataCache[one];
            //不自适应窗体变化
            if (!diaClass.options.autoResize) continue;
            offset = diaClass.options.offset;
            isArray = offset instanceof Array;
            isInNeed = needReset.indexOf(offset);

            if (!isArray && isInNeed === -1) continue;
            diaClass.setPosition();
        }
    });

    //拖拽中
    $doc.on('mousemove.' + plugName,
        function (e) {
            if (!dict.flag) return;
            //拖动标题
            if (dict.type === 0) {
                var left = dict.left + e.clientX - dict.X;
                var top = dict.top + e.clientY - dict.Y;
                dict.elem.css({
                    top: top + "px",
                    left: left + "px"
                });
                return;
            }

            //拉伸大小
            if (dict.type === 1) {
                rayui.log(e.clientX + "," + e.clientY);
                var width = dict.width + e.clientX - dict.X;
                var height = dict.height + e.clientY - dict.Y;
                width < dict.minWidth && (width = dict.minWidth);
                height < dict.minHeight && (height = dict.minHeight);

                dict.elem.css({
                    width: width,
                    height: "" //必须填写，防止书写height固定值时无法改变高度
                });
                dict.elemContent.outerHeight(height - dict.elemBtnbox.outerHeight());
            }

        }).on('mouseup.' + plugName,
            function (e) {
                if (dict.flag) {
                    dict.type === 1 && $(dict.shade).remove();
                    dict = {};
                }
            });

    layer.open = function (options) {
        var module = new LayerClass(options);
        return module.index;
    }

    layer.alert = function (msg, options, ok) {
        if (typeof options === "function") {
            ok = options;
            options = {};
        }
        return this.open($.extend(true,
            {
                content: msg,
                btns: [layer.btns.ok],
                btn0: ok || layer.close
            },
            options));
    }

    layer.msg = function (msg, options) {
        if (typeof msg === "object") {
            options = msg;
        }
        options = options || {};
        return this.open($.extend(true,
            {
                title: false,
                shadeClose: true,
                content: msg
            },
            options));
    }

    layer.confirm = function (msg, options, ok, cancel) {
        if (typeof options === "function") {
            cancel = ok;
            ok = options;
            options = {};
        }
        return this.open($.extend(true,
            {
                content: msg,
                btns: [layer.btns.ok, layer.btns.cancel],
                btn0: ok || layer.close,
                btn1: cancel || layer.close
            },
            options));
    }

    layer.prompt = function (title, options, ok, cancel) {
        if (typeof options === "number") {
            options = { ptype: options };
        } else if (typeof options === "function") {
            cancel = ok;
            ok = options;
            options = { ptype: 0 };
        }
        options = $.extend({
            inputFocus: true, //文本框自动获得焦点
            inputEnterBtn: 0 //文本框回车事件，数值，执行第inputEnterBtn按钮事件，负数不执行回车事件
        }, options);
        //type：0input 1textarea
        options.ptype = options.ptype || 0;
        
        var content = "",
            defaultValue = options.value || "",
            customClass = options.pclass ? ' ' + options.pclass : '';
        switch (options.ptype) {
            case 1:
                //password
                content = '<input type="password" class="layer-prompt-content rayui-input layer-input' +
                    customClass +
                    '"/>';
                break;
            case 2:
                //textarea
                content = '<textarea class="layer-prompt-content rayui-textarea layer-textarea' +
                    customClass +
                    '" >' +
                    defaultValue +
                    '</textarea>';
                break;
            default:
                //input
                content = '<input type="text" class="layer-prompt-content rayui-input layer-input' +
                    customClass +
                    '" value="' +
                    defaultValue +
                    '"/>';
                break;
        }

        var index = this.open($.extend(true,
            {
                title: title,
                content: content,
                btns: [layer.btns.ok, layer.btns.cancel],
                btn0: function (index) {
                    if (typeof ok === "function") {
                        var inputVal = $(this).closest(".layer-mainbox")
                            .find(".layer-contentbox .layer-prompt-content").val();
                        ok(index, inputVal);
                    } else {
                        layer.close(index);
                    }
                },
                btn1: cancel || layer.close
            },
            options));

        //事件增强
        var that = dataCache[index],
            $main = that.options.$main,
            $input = $main.find(".layer-contentbox").find("input:text,input:password,textarea"),
            $btn = options.inputEnterBtn > -1 ? $main.find('.layer-btnbox>.rayui-btn[data-index="' + options.inputEnterBtn + '"]') : null;
          
        //有文本框时自动获得焦点
        options.inputFocus && $input.focus();
        $btn && $btn.length > 0 && $input.on("keypress." + plugName, function (e) {
            if (e.keyCode === 13) {
                $(this).blur();
                var btnfunc = "btn" + that.options.inputEnterBtn, func = that.options[btnfunc];
                typeof func === "function" && func.call($btn[0], index, e);
            }
        });

        return index;
    }

    layer.loading = function (options) {
        options = options || {};
        if (typeof options === "number") {
            options = { icon: options };
        }
        options.title = false;
        options.type = 2;
        options.icon = options.icon || 0; //等待
        options.shadow = false;
        return this.open(options);
    }

    layer.iframe = function (options) {
        options = options || {};
        options.type = 1;
        options.minBtn = options.minBtn || true;
        options.maxBtn = options.maxBtn || true;
        options.content = options.src || options.content || "";
        options.icon = options.icon || 0;
        options.width = options.width || 600;
        options.height = options.height || 400;
        return this.open(options);
    }

    layer.tips = function (content, elem, options) {
        if (typeof content === "object") {
            options = content;
            content = null;
        }
        options = options || {};
        options.title = false;
        options.type = 3;
        options.elem = elem || options.elem;
        if (!options.elem) return "没有dom对象";
        options.content = content || options.content || "未设置提示消息";
        options.offset = options.offset || 6;
        options.shade = false;
        //options.timeout = 3000;
        options.bgColor = options.bgColor || "#333333";

        //关闭之前的tips
        var ii = $(options.elem).data("tipindex");
        if (ii >= 1000) layer.close(ii);

        ii = this.open(options);
        $(options.elem).data("tipindex", ii);
        return ii;
    }

    layer.close = function (index) {
        if (dataCache[index] === undef) return;
        var diaclass = dataCache[index],
            options = diaclass.options;

        //阻断循环close
        if (options.closing) return;
        options.closing = true;

        if (typeof options.onClose === "function") {
            try {
                //return false阻止关闭
                if (options.onClose(index) === false) return;
            } catch (e) { }
        }
        
        $("#layer-shade-" + index).remove();
        options.timerCloseIns && clearTimeout(options.timerCloseIns);
        var $main = options.$main;
        //html显示滚动条
        !options.scrollbar && $("html").removeClass("overflow-hidden");
        //dom对象回到body并隐藏
        options.contentParent && $main.find(options.content).hide().appendTo(options.contentParent);
        $main.remove();
        delete dataCache[index];
    }

    layer.closeAll = function () {
        for (var m in dataCache)
            layer.close(m);
    }

    layer.full = function (index) {
        if (dataCache[index] === undef) return;
        var diaclass = dataCache[index],
            options = diaclass.options;
        options.$main.find('.layer-toolbox .layer-btn-maximize').click();
    }

    isRayui ? rayui.define(function (exports) {
        exports(plugName, layer);
    }, rayui.jsAsync()) : (function () {
        window.rayui = {
            layer: layer
        };
    })();

})(window, jQuery);
